<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=\, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="get">get</button>
  <button id="post">post</button>
  <button>get</button>
  <button>get</button>
  <button>get</button>
  <button>get</button>
  <script>
    (() => {
      //get请求
      document.querySelector('#get').addEventListener('click', () => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', 'http://localhost:3000/users?id=1')
        xhr.send()
        xhr.addEventListener('load', () => {
          if (xhr.status >= 200) {
            console.log(xhr.responseText)
          }
        })
      })

    })();
    (() => {
      //post请求
      document.querySelector('#post').addEventListener('click', () => {
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'http://localhost:3000/users')

        //form编码 uname=zp&psd=123 
        //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        //xhr.send(`uname=zp&psd=123`)

        //json编码 JSON.stringify({ uname: 'xp', psd: '123' })
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify({ uname: 'xp', psd: '123' }))

        xhr.addEventListener('load', () => {
          if (xhr.status >= 200) {
            console.log(xhr.responseText)
          }
        })
      })
    })()

  </script>
</body>

</html>